const userlist = [
    {
        username: "admin",
        password: "admin",
        email: "admin@mail.com"
    }, 
    {
        username: "user",
        password: "user",
        email: "user@mail.com"
    },
    {
        username: "FOTOGARAFIE-YUK1",
        password: "12345678",
        email: "FOTOGARAFIE-YUK1@mail.com"
    }
]

$(document).ready(async function(){
    
    $('#register').on('submit', function(event) {
        event.preventDefault();

        var username = $('#reg-username').val();
        var email = $('#email').val();
        var password = $('#reg-password').val();
        var confirmPassword = $('#confirm-password').val();

        var validationMessage = validateRegistration(email, password, confirmPassword);

        
        if (validationMessage === "Registration is valid") {
            console.log("Registration is valid");
            sessionStorage.setItem('email', email);
            sessionStorage.setItem('password', password);
            sessionStorage.setItem('username', username);
            userlist.push({username: username, password: password, email: email});
            window.location.href = "../../index.html";
        } else {
            
            $('#errorMsg2').text(validationMessage);
        }
    });

    $('#login').on('submit', function(event) {
        event.preventDefault();
        var username = $('#log-username').val();
        var password = $('#password').val();
        // Validate the registration
        var validationMessage = validateLogin(username, password);
        console.log(validationMessage);
        if (validationMessage === "Login is valid") {
            sessionStorage.setItem('email', email);
            sessionStorage.setItem('password', password);
            sessionStorage.setItem('username', username);
            window.location.href = "../../index.html";
        } else {
            $('#errorMsg1').text(validationMessage);
        }
    });

    $('#to-login').click(function(){
        $('#login-form').show();
        $('#register-form').hide();
    });
    $('#to-sign').click(function(){
        $('#login-form').hide();
        $('#register-form').show();
    });

});


function validateRegistration(email, password, confirmPassword) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
        return "Invalid email";
    }

    if (password !== confirmPassword) {
        return "Passwords do not match";
    }

    if (password.length < 8) {
        return "Password should be at least eight characters long";
    }

    return "Registration is valid";
}

function validateLogin(username, password){
    console.log(username, password)
    for (var i = 0; i < userlist.length; i++) {
        if (userlist[i].username === username && userlist[i].password === password) {
            return "Login is valid";
        }
    }
    return "Invalid username or password";
}